package com.ahora.org.controller.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;

import com.ahora.org.ejb.jpa.entities.DocumentoUsuario;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.codec.Base64;

public class CrearPDF {
	
	
	public static void crearObservacionPDf(DocumentoUsuario documentoUsuario, String path) {
		try {
			System.out.println("ME HAN LLAMADO");
			Document pdfDocument = new Document();
	        Reader htmlreader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream (documentoUsuario.getObservacion())));
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        PdfWriter.getInstance(pdfDocument, baos);
	        pdfDocument.open();
	        StyleSheet styles = new StyleSheet();
	        styles.loadTagStyle("body", "font", "Bitstream Vera Sans");
	        ArrayList arrayElementList = HTMLWorker.parseToList(htmlreader, styles);
	        for (int i = 0; i < arrayElementList.size(); ++i) {
	            Element e = (Element) arrayElementList.get(i);
	            pdfDocument.add(e);
	        }
	        pdfDocument.close();
	        byte[] bs = baos.toByteArray();
	        String pdfBase64 = Base64.encodeBytes(bs); //output
	        File pdfFile = new File(path);
	        FileOutputStream out = new FileOutputStream(pdfFile);
	        out.write(bs);
	        out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	        
	
	}
}
